// 使用对象存储常量
const CategoryGoodConfig = {
	ITEM_CLASS: 'category_list_item'
}

class CategoryGood {

	constructor({
		data = [],
		container = 'category_list',
		parentContainer = 'scroll_container',
		onClickItem = () => {}
	}) {
		this.data = data;
		this.container = document.getElementById(container);
		this.parentContainer = document.getElementById(parentContainer);
		this.onClickItem = onClickItem;
		this.render();
	}

	render() {
		if (this.data.length == 0) return;
		this.container.innerHTML = '';
		const html = this.data.map((item, index) =>
			this.generateTabItem(item, index)
		).join('');
		this.container.innerHTML = html;

		//纯原生写法，不依赖jquery
		this.container.addEventListener('click', e => {
			const itemElement = e.target.closest(`.${CategoryGoodConfig.ITEM_CLASS}`);
			if (itemElement) {
				const itemData = JSON.parse(itemElement.dataset.item);
				this.onClickItem(itemData); // 触发外部回调
			}
		})
	}

	generateTabItem(item, index) {
		let children = item.children;
		let itemHtml = `<div class="category_section" id="${item.groupId}">${item.name}</div>`;
		if (children && children.length > 0) {
			itemHtml += `<div class="category_list">`;
			for (let i = 0, len = children[0].children.length; i < len; i++) {
				let subItem = children[0].children[i];
				let cover = subItem.thumbnail;
				//let cover = 'https://img14.360buyimg.com/n5/s720x720_jfs/t20260625/310228/4/12150/205972/685ae704Fa53ea50e/ec6cfd8791307b7d.png'
				itemHtml += `<div class="${CategoryGoodConfig.ITEM_CLASS}" data-item='${escapeHtml(JSON.stringify(subItem))}'>
								<img src="${cover}" class="cimg" />
								<span class=text-mline>${subItem.name}</span>
							</div>`
			}
			itemHtml += `</div>`
		}
		return itemHtml
	}

	scrollLocation(target) {
		const targetElement = document.getElementById(target);
		if (!this.parentContainer || !targetElement) return;
		const targetRect = targetElement.getBoundingClientRect();
		const containerRect = this.parentContainer.getBoundingClientRect();
		this.parentContainer.scrollTo({
			top: targetRect.top - containerRect.top + this.parentContainer.scrollTop,
			behavior: 'smooth'
		});
	}
	
	update(newData) {
		this.data = newData;
		this.render();
	}
}
